package com.fubowen.lepton.ui.container.children.download.recycler

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SortedList
import com.fubowen.lepton.conf.FileConfig
import com.fubowen.lepton.databinding.FragmentDownloadItemBinding
import com.fubowen.lepton.helper.ViewHelper.setVisible
import com.fubowen.lepton.ui.container.children.visited.recycler.OnItemClickListener

class DownloadAdapter : RecyclerView.Adapter<DownloadAdapter.ViewHolder>() {

    private var _onItemClickListener: OnItemClickListener? = null
    private var _dataSource: SortedList<FileConfig>? = null

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        _onItemClickListener = onItemClickListener
    }

    fun setDataSource(list: SortedList<FileConfig>) {
        _dataSource = list
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            FragmentDownloadItemBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        _dataSource?.apply {
            val item = get(position)
            holder.title.text = item.fullName
            holder.size.text = item.size
        }
    }

    override fun getItemCount(): Int = _dataSource?.size() ?: 0

    inner class ViewHolder(binding: FragmentDownloadItemBinding) :
        RecyclerView.ViewHolder(binding.root) {

        val title: TextView = binding.downloadItemTitle
        val size: TextView = binding.downloadItemSize
        private val delete = binding.downloadItemDelete
        private val deleteOk = binding.downloadItemDeleteOk
        private val deleteCancel = binding.downloadItemDeleteCancel

        init {
            delete.setOnClickListener {
                delete.setVisible(false)
                deleteOk.setVisible(true)
            }
            deleteOk.setOnClickListener {
                delete.setVisible(true)
                deleteOk.setVisible(false)
                _onItemClickListener?.onRemoveClick(this.itemView)
            }
            deleteCancel.setOnClickListener {
                delete.setVisible(true)
                deleteOk.setVisible(false)
            }
            this.itemView.setOnClickListener {
                _onItemClickListener?.onClick(this.itemView)
            }
        }
    }
}